home *** CD-ROM | disk | FTP | other *** search
/ Cream of the Crop 21 / Cream of the Crop 21 (Terry Blount) (October 1996).iso / comm / msged400.zip / src / memextra.c < prev    next >
C/C++ Source or Header  |  1996-06-27  |  2KB  |  86 lines

  1. /*
  2.  *  MEMEXTRA.C
  3.  *
  4.  *  Written 1995-1996 by Andrew Clarke and released to the public domain.
  5.  *
  6.  *  Memory allocation routines with core exhaust checking.
  7.  */
  8.  
  9. #include <stdlib.h>
  10. #include "msged.h"
  11. #include "mprotos.h"
  12. #include "memextra.h"
  13.  
  14. static char msg_alloc_fail[] =
  15. "*** Memory allocation failure (out of memory)\n"
  16. "*** Needed %u (%Xh) bytes.\n";
  17.  
  18. static char msg_realloc_fail[] =
  19. "*** Memory reallocation failure (out of memory)\n"
  20. "*** Needed %u (%Xh) bytes.\n";
  21.  
  22. static char msg_free_fail[] =
  23. "*** Memory deallocation failure (attempted to free null pointer)\n";
  24.  
  25. void *xmalloc(size_t size)
  26. {
  27.     void *ptr;
  28.     ptr = malloc(size);
  29.     if (ptr == NULL)
  30.     {
  31.         cleanup(msg_alloc_fail, (unsigned)size, (unsigned)size);
  32.         exit(0);
  33.     }
  34.     return ptr;
  35. }
  36.  
  37. void *xcalloc(size_t nmemb, size_t size)
  38. {
  39.     void *ptr;
  40.     ptr = calloc(nmemb, size);
  41.     if (ptr == NULL)
  42.     {
  43.         cleanup(msg_alloc_fail, (unsigned)(nmemb * size), (unsigned)(nmemb * size));
  44.         exit(0);
  45.     }
  46.     return ptr;
  47. }
  48.  
  49. void *xrealloc(void *ptr, size_t size)
  50. {
  51.     if (ptr == NULL)
  52.     {
  53.         return xmalloc(size);
  54.     }
  55.     if (size == (size_t) 0)
  56.     {
  57.         xfree(ptr);
  58.         return NULL;
  59.     }
  60.     ptr = realloc(ptr, size);
  61.     if (ptr == NULL)
  62.     {
  63.         cleanup(msg_realloc_fail, (unsigned)size, (unsigned)size);
  64.         exit(0);
  65.     }
  66.     return ptr;
  67. }
  68.  
  69. char *xstrdup(const char *str)
  70. {
  71.     return strcpy(xmalloc(strlen(str) + 1), str);
  72. }
  73.  
  74. void xfree(void *ptr)
  75. {
  76.     if (ptr == NULL)
  77.     {
  78.         cleanup(msg_free_fail);
  79.         exit(0);
  80.     }
  81.     else
  82.     {
  83.         free(ptr);
  84.     }
  85. }
  86.